﻿CREATE PROCEDURE [dbo].[Forum_Thread_Get]
	@threadId BIGINT,
	@userId UNIQUEIDENTIFIER
AS
BEGIN
	DECLARE @now DATETIME = GETUTCDATE()

	SELECT s.[HashTag] AS [SectionHashTag]
				,th.[IsSolved]
				,th.[Name]
				,th.[CreatedBy]
				,th.[CreateDate]
				,th.[UpdateBy]
				,th.[UpdateDate]
	FROM [dbo].[forum_Thread] AS th
	INNER JOIN [dbo].[forum_Section] AS s ON th.[SectionId] = s.[SectionId]
	WHERE [ThreadId] = @threadId

	SELECT n.[ThreadNoteId]
      ,n.[Text]
      --,n.[ThreadId]
      --,n.[Order]
      --,n.[CreatedBy]
      ,n.[CreatedDate]
      ,n.[UpdatedBy]
      ,n.[UpdatedDate]
			,u.[NickName]
			,u.[EmailSh1]
			,CAST(
				CASE WHEN @userId = n.[CreatedBy] AND DATEDIFF(minute, n.[CreatedDate], @now) < 1500000
					THEN 1
					ELSE 0
					END
			AS BIT) AS 'AllowEdit'
  FROM [dbo].[forum_ThreadNote] AS n
	INNER JOIN [dbo].[user_User] AS u ON u.[UserId] = n.[CreatedBy]
	WHERE n.[ThreadId] = @threadId
	ORDER BY n.[Order] ASC

	SELECT c.[ClarifyNoteId]
      ,c.[Text]
      ,c.[ThreadNoteId]
      --,c.[CreatedBy]
      ,c.[CreatedDate]
      ,c.[UpdatedBy]
      ,c.[UpdatedDate]
			,c.[Order]
			,u.[NickName]
			,u.[EmailSh1]
			,CAST(
				CASE WHEN @userId = c.[CreatedBy] AND DATEDIFF(minute, c.[CreatedDate], @now) < 1500000
					THEN 1
					ELSE 0
					END
			AS BIT) AS 'AllowEdit'
  FROM [dbo].[forum_ClarifyNote] AS c
	INNER JOIN [dbo].[user_User] AS u ON u.[UserId] = c.[CreatedBy]
	WHERE c.[ThreadNoteId] IN (	SELECT [ThreadNoteId]
														FROM [dbo].[forum_ThreadNote]
														WHERE [ThreadId] = @threadId)



	DECLARE @hashTag NVARCHAR(64)
	SELECT @hashTag = s.[HashTag]
	FROM [dbo].[forum_Thread] AS th
	INNER JOIN [dbo].[forum_Section] AS s ON th.[SectionId] = s.[SectionId]
	WHERE [ThreadId] = @threadId

	--EXEC [dbo].[Forum_Thread_Crumb] @hashTag = @hashTag
END